# -*- coding: utf-8 -*-
# author: AZJ
# date: 2024/11/13
# 假如命运扼住了你的咽喉，你就去挠她的咯吱窝
import time
from selenium import webdriver
from selenium.common import TimeoutException, NoSuchElementException
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

from hongruan.finance_pom.opdata import OpData


class Page:
    uname = ('id', 'username')
    pwd = ('id', 'password')
    login_btn = ('id', 'login_btn')
    re_pwd = ('id', 'repassword')
    enter_key = Keys.ENTER
    def __init__(self):
        self.web = self.get_driver()

    def open(self):
        web = self.web

    def find_element(self, web, *locator):
        try:
            print("定位元素:%s" % (locator,))
            return WebDriverWait(web, 3).until(EC.presence_of_element_located(*locator))
        except Exception as msg:
            print(u"页面中未能找到 %s 元素" % locator)
            print("错误信息%s" % msg)
            return None

    def send_keys(self, web, *locator, value, is_clear=True):
        element = self.find_element(web, *locator)
        if is_clear:
            element.clear()
            element.send_keys(value)
        else:
            element.send_keys(value)
        print("输入值:%s" % value)
    def get_driver(self):
        driver = webdriver.Chrome()
        return driver

    def new_page(self, url):
        web = self.web
        web.execute_script(f"window.open('{url}');")
        web.switch_to.window(web.window_handles[1])

    def swift_url(self, web, url):
        web.get(url)

    def login_dir(self, username, password):
        web = self.web
        self.swift_url(web, 'http://127.0.0.1:90')
        self.send_keys(web, self.uname, value=username)
        self.send_keys(web, self.pwd, value=password)
        lgbtn = self.find_element(web, self.login_btn)
        lgbtn.click()

    def login(self, username, password):
        web = self.web
        self.login_dir(username, password)
        check_uname = ('xpath', '/html/body/div[1]/div/div/form/div[1]/span[1]')
        check_pwd = ('xpath', '/html/body/div[1]/div/div/form/div[2]/span[1]')
        username_not_exit = self.find_element(web, check_uname)
        password_not_exit = self.find_element(web, check_pwd)
        result = [web.title]
        if username_not_exit is not None:
            try:
                result.append(username_not_exit.text)
            except Exception:
                pass
        if password_not_exit is not None:
            try:
                result.append(password_not_exit.text)
            except Exception:
                pass
        return result

    def register(self, username, password, repassword):
        web = self.web
        chk_uname = ('xpath', '/html/body/div[1]/div/div/form/div[1]/span[1]')
        chk_pwd = ('xpath', '/html/body/div[1]/div/div/form/div[2]/span[1]')
        chk_re_pwd = ('xpath', '/html/body/div[1]/div/div/form/div[3]/span[1]')
        self.swift_url(web, 'http://127.0.0.1:90/toregister.html')
        self.send_keys(web, self.uname, value=username)
        self.send_keys(web, self.pwd, value=password)
        self.send_keys(web, self.re_pwd, value=repassword)
        self.send_keys(web, self.re_pwd, value=self.enter_key, is_clear=False)
        time.sleep(0.5)
        result = [web.title]
        if self.find_element(web, chk_uname) is not None:
            result.append(self.find_element(web, chk_uname).text)
        if self.find_element(web, chk_pwd) is not None:
            result.append(self.find_element(web, chk_pwd).text)
        if self.find_element(web, chk_re_pwd) is not None:
            result.append(self.find_element(web, chk_re_pwd).text)
        return result

    def bank_add_card(self, card_name, card_number):
        web = self.web
        opdata = OpData()
        card_num = len(opdata.db_data('bankcard','cardBank','userId',1))
        add_btn = ('id', 'bankCard_add_modal_btn')
        bk_name = ('id', 'cardBank_add_input')
        cd_num = ('id', 'cardNum_add_input')
        cmt_btn = ('id', 'bankCard_save_btn')
        cmt = self.find_element(web, cmt_btn)
        add_bt = self.find_element(web, add_btn)
        add_bt.click()
        time.sleep(0.5)
        self.send_keys(web, bk_name, value=card_name)
        self.send_keys(web, cd_num, value=card_number)
        cmt.click()
        card_num2 = len(opdata.db_data('bankcard','cardBank','userId',1))
        return card_num2 - card_num

    def bank_del_card(self, card_name):
        web = self.web
        opdata = OpData()
        card_num = len(opdata.db_data('bankcard','userId','cardBank',1))
        enter_btn = ('xpath', f'//button[contains(text(), "{card_name}")]')
        del_btn = ('xpath', '/html/body/div/div/main/div/div/div[4]/div/div/div[1]/ul/li/button[2]')
        self.find_element(web, del_btn).click()
        time.sleep(0.3)
        self.find_element(web, enter_btn).click()
        card_num2 = len(opdata.db_data('bankcard','userId','cardBank',1))
        return card_num2 - card_num

    def bank_change_card(self, card_name, card_number, state):
        web = self.web
        op_data = OpData()
        edit_btn = ('xpath', '/html/body/div/div/main/div/div/div[3]/div/div/div[1]/ul/li/button[1]')
        card_bank = ('id', 'cardBank_update_input')
        chk_bank = ('xpath', '//*[@id="bankCardUpdateModal"]/div/div/div[2]/form/div[1]/div[1]/span')
        card_num = ('id', 'cardNum_update_input')
        truth_span = ('xpath','//*[@id="bankCardUpdateModal"]/div/div/div[2]/form/div[2]/div[1]/div/label[2]')
        update_btn = ('xpath', '//button[contains(text(), "更新")]')
        self.find_element(web, edit_btn).click()
        time.sleep(0.3)
        result = ''
        if state == '银行名':
            self.send_keys(web, card_bank, value=card_name)
            self.find_element(web, update_btn).click()
            tmp = self.find_element(web, chk_bank)
            result = tmp.text
        elif state == '卡号':
            self.send_keys(web, card_num, value=card_number)
            self.find_element(web, update_btn).click()
            tmp = op_data.db_data('bankcard','cardNum','cardBank','伊朗中央银行')
            result = tmp[0][0]
        elif state == '类别':
            self.find_element(web, truth_span).click()
            self.find_element(web, update_btn).click()
            tmp = op_data.db_data('bankcard','type','cardBank','伊朗中央银行')
            result = tmp[0][0]
        return result

    def bank_card(self, card_name, card_number, state):
        web = self.web
        self.login_dir('lisi', '123456')
        time.sleep(0.3)
        self.swift_url(web, 'http://127.0.0.1:90/user/personal/toBankCard.html')
        result = ''
        if state == "增加":
            card_num = self.bank_add_card(card_name, card_number)
            result = str(card_num)
        if state == "删除":
            card_num = self.bank_del_card(card_name)
            result = str(card_num)
        if "修改" in state:
            change_state = state.replace('修改','')
            result = self.bank_change_card(card_name, card_number, change_state)
        return result

    def finance_buy(self, state, username, pay_password):
        web = self.web
        op_data = OpData()
        jijin_btn = ('xpath', '/html/body/div/div/main/div/div/div/div/div[2]/div/table/tbody/tr[1]/td[9]/button')
        qixian_btn = ('xpath', '/html/body/div/div/main/div/div/div/div/div[2]/div/table/tbody/tr[1]/td[8]/button')
        lingqian_btn = ('xpath', '/html/body/div[1]/div/main/div/div/div/div/div[2]/div/table/tbody/tr[2]/td[6]/button')
        yes_btn = ('xpath','//a[contains(text(),"确定")]')
        buy_failed = ('xpath','//div[contains(text(),"买入失败")]')
        pay_password_input = ('xpath','/html/body/div[3]/div[2]/input')
        user_id = (op_data.db_data('user','id','username',username))[0][0]
        before_balance = op_data.db_data('bankcard', 'balance', 'userId', f'{user_id}" and defaultl=1#')
        if state == "零钱理财":
            self.swift_url(web, "http://127.0.0.1:90/user/finance/toChangeMoney.html")
            self.find_element(web,lingqian_btn).click()
        if state == "期限理财":
            self.swift_url(web, "http://127.0.0.1:90/user/finance/toTermFinancial.html")
            self.find_element(web,qixian_btn).click()
        if "基金理财" in state:
            tmp = state.split(',')
            # print("---------------------",tmp, len(tmp))
            if type(tmp) == list and len(tmp) >= 3:
                self.swift_url(web,"http://127.0.0.7:90/user/personal/toBankCard.html")
                if '1' in tmp[2]:
                    try:
                        web.find_element(By.XPATH,'/html/body/div/div/main/div/div/div[2]/div/div/div[1]/ul/li/button[3]').click()
                        before_balance = op_data.db_data('bankcard', 'balance', 'userId', f'{user_id}" and defaultl=1#')
                    except NoSuchElementException:
                        pass
                elif '2' in tmp[3]:
                    try:
                        web.find_element(By.XPATH,'/html/body/div/div/main/div/div/div[3]/div/div/div[1]/ul/li/button[3]').click()
                        before_balance = op_data.db_data('bankcard', 'balance', 'userId', f'{user_id}" and defaultl=1#')
                    except NoSuchElementException:
                        pass
            self.swift_url(web, "http://127.0.0.1:90/user/finance/toFundProduct.html")
            time.sleep(0.3)
            self.find_element(web,jijin_btn).click()
        self.send_keys(web, pay_password_input, value=pay_password)
        self.find_element(web, yes_btn).click()
        time.sleep(0.3)
        if pay_password == "666667" or username == 'lisi5' or username == 'lisi4' or username == 'lisi6':
            result_alert = self.find_element(web, buy_failed)
            result = result_alert.text
        else:
            after_balance = op_data.db_data('bankcard', 'balance', 'userId', f'{user_id}" and defaultl=1#')
            print(after_balance, before_balance)
            result = (int(before_balance[0][0]) - int(after_balance[0][0]))
        return result

    def bank_finance_buy(self, state, username, password, pay_password):
        web = self.web
        self.login_dir(username, password)
        time.sleep(0.5)
        result = self.finance_buy(state,username,pay_password)
        return result

    def debit(self, state, username, password, amount, day):
        web = self.web
        op_data = OpData()
        yes_btn = ('xpath', '//button[contains(text(),"确认")]')
        amount_input = ('id', 'amount')
        term_input = ('id', 'term')
        submit_btn = ('id', 'submit')
        tmp_btn = ('xpath','//a[contains(text(),"系统首页")]')
        user_id = (op_data.db_data('user', 'id', 'username', username))[0][0]
        self.login_dir(username, password)
        time.sleep(0.3)
        self.swift_url(web, "http://127.0.0.1:90/user/tools/toApplyLoan.html")
        before_count = (op_data.db_data('loan','count(userId)','userId',user_id))[0][0]
        self.send_keys(web, amount_input, value=amount)
        self.send_keys(web, term_input, value=day)
        self.find_element(web, submit_btn).click()
        time.sleep(0.3)
        self.find_element(web, yes_btn).click()
        after_count = (op_data.db_data('loan','count(userId)','userId',user_id))[0][0]
        result =  int(after_count) - int(before_count)
        if state == '2':
            before_balance = op_data.db_data('bankcard', 'balance', 'userId', f'{user_id}" and defaultl=1#')
            pass_update = ('xpath','/html/body/div/div/main/div/div/div/div/div[2]/div/table/tbody/tr[1]/td[7]/button[1]')
            self.new_page('http://127.0.0.1:90')
            self.login_dir('admin','123456')
            time.sleep(0.3)
            self.swift_url(web, 'http://127.0.0.1:90/admin/loan/toLoanexam.html')
            self.find_element(web,pass_update).click()
            time.sleep(0.3)
            self.find_element(web,yes_btn).click()
            time.sleep(0.3)
            after_balance = op_data.db_data('bankcard', 'balance', 'userId', f'{user_id}" and defaultl=1#')
            result = (int(after_balance[0][0]) - int(before_balance[0][0]))
        return result

# page = Page()
# print("安振杰".split('123'))
# result = page.bank_card('国家银行','1234567891234567', '增加')
# print(result)
# page.find_element(web,())
# wait = WebDriverWait(web, 10)
# print(wait.until(EC.presence_of_element_located()))